<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\command;

use app\enum\ServiceCostEnum;
use app\model\TaskAccountCompareModel;
use app\service\cost\TaskAccountService;
use think\console\Input;
use think\console\Output;
use think\facade\Cache;

class MediaCostCompareListWork extends BaseWork
{
    public const REDIS_TASK_KEY = ServiceCostEnum::CACHE_CONFIG['media_cost_compare_list'];

    protected function configure()
    {
        // 指令配置
        $this->setName('media_cost_compare_list_work');
        // 设置参数
        $this->setDescription('存储回溯数据结果处理脚本队列脚本')
            ->setHelp('php think media_cost_compare_work');
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        $redis = Cache::store('redis')->handler();
        $key = self::REDIS_TASK_KEY;
        $output->writeln('=======存储回溯数据结果处理脚本队列开始' . date('Y-m-d H:i:s', time()) . '=======');
        try {
            // 获取所有有效账户
            (new TaskAccountCompareModel())->where('new_task_account_id > 0')->chunk(100, function ($items) use ($output, $redis, $key) {
                if ($items) {
                    foreach ($items as $item) {
                        // 存入redis队列
                        $res = $redis->rPush($key, $item->getKey());
                        if (! $res) {
                            $output->writeln('=======存储回溯数据结果处理脚本队列失败,报表id:' . $item->getKey() . TaskAccountService::getError(0) . date('Y-m-d H:i:s', time()) . '=======');
                        }
                    }
                } else {
                    return false;
                }
            }, 'id', 'DESC');
        } catch (\Exception $e) {
            $output->writeln('=======存储回溯数据结果处理脚本队列失败,报表id:' . $e->getMessage() . date('Y-m-d H:i:s', time()));
        }
        $output->writeln('=======回溯数据结果处理结束' . date('Y-m-d H:i:s', time()) . '=======');
    }
}
